class Solution
{
public:
    int sumImbalanceNumbers(vector<int> &nums)
    {
        int n = nums.size();
        int result = 0;
        for (int start = 0; start < n; ++start)
        {
            unordered_set<int> s;
            s.insert(nums[start]);

            int inbalanceNum = 0;
            for (int end = start + 1; end < n; ++end)
            {
                if (!s.count(nums[end]))
                {
                    bool pExist = s.count(nums[end] + 1);
                    bool mExist = s.count(nums[end] - 1);
                    if (pExist && mExist)
                    {
                        inbalanceNum -= 1;
                    }
                    else if (!pExist && !mExist)
                    {
                        inbalanceNum += 1;
                    }
                    s.insert(nums[end]);
                }

                result += inbalanceNum;
            }
        }
        return result;
    }
};